package com.fcai.microserv.autoconfigure.cors;

import lombok.AllArgsConstructor;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Objects;

@Configuration
@EnableConfigurationProperties(CorsProperties.class)
@ConditionalOnProperty(prefix = CorsProperties.PREFIX, value = "enabled", matchIfMissing = true)
@AllArgsConstructor
public class CorsConfiguration {
    private final CorsProperties corsProperties;

    private org.springframework.web.cors.CorsConfiguration buildConfig() {
        org.springframework.web.cors.CorsConfiguration corsConfiguration = new org.springframework.web.cors.CorsConfiguration();
        for(String origin: Objects.requireNonNull(corsConfiguration.getAllowedOrigins())) {
            corsConfiguration.addAllowedOrigin(origin);
        }
        if (ArrayUtils.isEmpty(corsProperties.getAllowedOrigins())) {
            corsConfiguration.addAllowedOrigin("*"); //
        }

        for (String header: Objects.requireNonNull(corsConfiguration.getAllowedHeaders())) {
            corsConfiguration.addAllowedHeader(header);
        }
        if (ArrayUtils.isEmpty(corsProperties.getAllowedHeaders())) {
            corsConfiguration.addAllowedHeader("*");
        }

        for (String header: Objects.requireNonNull(corsConfiguration.getAllowedMethods())) {
            corsConfiguration.addAllowedMethod(header);
        }
        if (ArrayUtils.isEmpty(corsProperties.getAllowedMethods())) {
            corsConfiguration.addAllowedMethod("*");
        }

        corsConfiguration.setAllowCredentials(corsProperties.isAllowCredentials()); // 设置是否允许发送cookie
        corsConfiguration.setMaxAge(corsProperties.getMaxAge()); // 设置preflight请求的有效时间
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        // cors配置允许跨域
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig()); // 4
        return new CorsFilter(source);
    }
}
